/**
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.kopsox.environment.impl;

import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;

import org.kopsox.comm.listener.Observer;
import org.kopsox.data.ContainerDescriptor;
import org.kopsox.data.ValueDescriptor;
import org.kopsox.data.container.ValueContainer;
import org.kopsox.data.container.impl.ContainerDescriptorImpl;
import org.kopsox.data.container.impl.ValueContainerImpl;
import org.kopsox.data.impl.Polymorph;
import org.kopsox.environment.ContainerEnvironment;
import org.kopsox.environment.ValueEnvironment;
import org.kopsox.environment.proxy.EnvironmentPropertiesEnum;
import org.kopsox.environment.proxy.KopsoxRegistry;
import org.kopsox.general.priority.impl.PriorityImpl;
import org.kopsox.general.type.ValueType;
import org.kopsox.general.type.ValueTypeEnum;
import org.kopsox.util.xml.data.XMLContainerDescriptor;
import org.kopsox.util.xml.data.impl.NameNamespaceKey;
import org.kopsox.util.xml.data.impl.NamePriorityDescriptor;
import org.kopsox.util.xml.parser.XMLParserFactory;
import org.kopsox.util.xml.parser.exception.KopsoxXMLParserException;
import org.kopsox.util.xml.parser.impl.ContainerXMLParser;
import org.kopsox.validation.ContainerValidator;

/**
 * @author Konrad Renner - 15.10.2010
 *
 */
public class ContainerEnvironmentImpl implements ContainerEnvironment {

	private final Map<String, XMLContainerDescriptor> containers;
	
	private volatile boolean initialized;
	
	public ContainerEnvironmentImpl(){
		this.containers = new HashMap<String, XMLContainerDescriptor>();
		this.initialized = false;
	}

	/* (non-Javadoc)
	 * @see org.kopsox.environment.KopsoxEnvironment#initialize()
	 */
	@Override
	public synchronized boolean initialize(final Properties properties) {
		if(!this.initialized && properties != null){
			String pathToXml = properties.getProperty(EnvironmentPropertiesEnum.PATHTO_CONTAINER_XML.toString());
			
			if(pathToXml == null){
				return false;
			}
			
			try {
				ContainerXMLParser parser = XMLParserFactory.getXMLParser(ContainerXMLParser.class, pathToXml);
				
				parser.parseXML();
				
				List<XMLContainerDescriptor> descriptors = parser.getContainerDescriptors();
				
				for(XMLContainerDescriptor desc: descriptors){
					containers.put(desc.getName(), desc);
				}
				
				this.initialized = true;
			} catch (KopsoxXMLParserException e) {
				e.printStackTrace();
				return false;
			}
		}
		
		return this.initialized;
	}

	/* (non-Javadoc)
	 * @see org.kopsox.environment.ContainerEnvironment#getValueContainer(String name)
	 */
	@Override
	public ValueContainer getValueContainer(String name) {
		
		if(!this.initialized || !this.containers.containsKey(name)){
			return new ValueContainerImpl();
		}
		
		XMLContainerDescriptor desc = this.containers.get(name);
		
		
		try {
			Class<?> clazz = Class.forName(desc.getClassName());
			
			ValueContainer container;
			
			//if the container is an instance of ValueEntity, create it with the correct key-names
			try {
				Object[] conArr = {desc.getKeyNames()};
				
				Constructor<?> constructor = clazz.getConstructor(Set.class);
				
				container = (ValueContainer) constructor.newInstance(conArr);
			}catch(InstantiationException e) {
				container = (ValueContainer) clazz.newInstance();
			}catch (NoSuchMethodException e) {
				container = (ValueContainer) clazz.newInstance();
			}
			
			//Create an Container Descriptor
			ContainerDescriptor contdesc = new ContainerDescriptorImpl.ContainerDescriptorBuilder(desc.getName()).namespace(desc.getNamespace()).isAutoErrorDelegationEnabled(desc.isAutoErroDelegationEnabled()).isAutoValidationEnabled(desc.isAutoValidationEnabled()).build();
			container.setDescriptor(contdesc);
			
			//Add the Values
			ValueEnvironment valueenv = KopsoxRegistry.INSTANCE.getValueEnvironment();
			for(NameNamespaceKey key:desc.getValues()){
				
				//Read the values from the Environment
				ValueDescriptor valdesc = valueenv.getValueDescription(key.getName(), key.getNamespace());
				
				if(valdesc != null){
					
					
					String initval = valueenv.getInitialDataFromValue(key.getName(), key.getNamespace());
					String type = valueenv.getTypeNameFromValue(key.getName(), key.getNamespace());
					
					try {
						//Create the Value
						Object o = createValue(initval, type);
						
						Polymorph<Serializable> value = new Polymorph<Serializable>((Serializable)o,valdesc);
						value.addAllObservers(valueenv.getObserversForValue(key.getName(), key.getNamespace()));
						value.addAllValidators(valueenv.getValidatorsForValue(key.getName(), key.getNamespace()));
						
						//Add to the container
						container.setValue(key.getName(), value);
						
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (SecurityException e) {
						e.printStackTrace();
					} 
					
				}
				
			}
			
			//Add Observers to the container
			Collection<NamePriorityDescriptor> observers = desc.getObservers();
			
			for(NamePriorityDescriptor npdesc:observers){
				
				try {
					Class<?> obsclazz = Class.forName(npdesc.getName());
					
					Observer obs = (Observer) obsclazz.newInstance();
					
					try{
						obs.setPriority(new PriorityImpl(Integer.parseInt(npdesc.getPriority())));
					}catch(NumberFormatException e){
						e.printStackTrace();
					}
					
					container.addObserver(obs);
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} 
			}
			
			//Add the Validators
			container.addAllContainerValidators(getValidatorsForContainer(desc.getValidators()));
			
			return container;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		return  new ValueContainerImpl();
	}
	
	private final Object createValue(String value,String type) throws IllegalArgumentException, ClassNotFoundException, SecurityException{
		Class<?> clazz = Class.forName(type);
		
		ValueType valueType = ValueTypeEnum.getTypeFromClass(clazz);
		
		return valueType.convert(value);
	}
	
	private final Collection<ContainerValidator> getValidatorsForContainer(Collection<NamePriorityDescriptor>  validators) {
		
		Collection<ContainerValidator> ret = new TreeSet<ContainerValidator>();
		
		if(validators != null) {
			for(NamePriorityDescriptor npdesc:validators){
				
				//Read the Validators from the KopsoxRegistry
				ContainerValidator val = (ContainerValidator)KopsoxRegistry.INSTANCE.getValidatorEnvironment().getValidator(npdesc.getName());
				
				if(val != null){
					try{
						val.setPriority(new PriorityImpl(Integer.parseInt(npdesc.getPriority())));
					}catch(NumberFormatException e){
						e.printStackTrace();
					}
					
					ret.add(val);
				}
			}
		}
		
		return ret;
	}
}
